package com.combetter.changxing.ui.activity;


import android.bluetooth.BluetoothGatt;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;

import com.jakewharton.rxbinding2.view.RxView;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.combetter.changxing.MyApp;
import com.combetter.changxing.R;
import com.combetter.changxing.adapter.BaseQAdapter;
import com.combetter.changxing.bluetooth.FacilityClient2;
import com.combetter.changxing.databinding.ActivityMineCollectBinding;
import com.combetter.changxing.databinding.ActivityMineCollectItemBinding;
import com.combetter.changxing.db.entity.Collect;
import com.combetter.changxing.model.EventMessage;
import com.combetter.changxing.ui.base.BaseActivity;
import com.combetter.changxing.ui.base.BaseBindingViewHolder;
import com.combetter.changxing.ui.dialog.RxDialogSureCancel;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.MineCollectViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


/**
 * 我的收藏
 * <p>
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/12.
 */
public class MineCollectActivity extends BaseActivity<ActivityMineCollectBinding, MineCollectViewModel> {
    private CollectAdapter adapter;

    @Override
    public int setLayout() {
        EventBus.getDefault().register(this);
        return R.layout.activity_mine_collect;
    }

    @Override
    public void init() {
        /**
         *  下拉刷新
         */
        mBinding.srlContent.setDisableContentWhenRefresh(true);
        mBinding.srlContent.setHeaderHeight(80);
        mBinding.srlContent.setRefreshHeader(new ClassicsHeader(this));
        mBinding.srlContent.setOnRefreshListener(refreshlayout -> mViewModel.selectCollect(mBinding.srlContent));

        adapter = new CollectAdapter(null);
        mBinding.recycler.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recycler.setAdapter(adapter);

    }

    @Override
    public Class createViewModel() {
        return MineCollectViewModel.class;
    }

    @Override
    public void loadData() {
        mBinding.srlContent.autoRefresh();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventData(EventMessage message) {
        switch (message.getType()) {
            /**
             *  获得收藏数据回调
             */
            case "selectCollect":
                if (MyApp.getInstance().getDatabase().collectDao() != null) {
                    List<Collect> collects = MyApp.getInstance().getDatabase().collectDao().getCollectInfoList();
                    if (collects != null&&collects.size()>0) {
                        adapter.setNewData(collects);
                    }else {
                        adapter.getData().clear();
                        adapter.notifyDataSetChanged();
                    }
                }
                break;
            /**
             *  取消收藏回调
             */
            case "updateSmoke":
                mBinding.srlContent.autoRefresh();
                break;
        }
    }

    /**
     * 收藏adapter
     */
    class CollectAdapter extends BaseQAdapter<Collect, ActivityMineCollectItemBinding, BaseBindingViewHolder<ActivityMineCollectItemBinding>> {

        public CollectAdapter(@Nullable List<Collect> data) {
            super(R.layout.activity_mine_collect_item, data);
        }

        @Override
        protected void convert(BaseBindingViewHolder helper, Collect item) {
            ActivityMineCollectItemBinding mBinding = (ActivityMineCollectItemBinding) helper.getDataViewBinding();
            mBinding.setCollect(item);

            int position = item.getGoodsName().indexOf("_");
            if (position != -1) {
                String brand2 = item.getGoodsName().substring(0, position);
                String model2 = item.getGoodsName().substring(position + 1, item.getGoodsName().length());
                mBinding.tvTrademark.setText(brand2);
                mBinding.tvGoodsName.setText(model2);
            }

            /**
             *  取消收藏
             */
            RxView.clicks(mBinding.tvCancel).subscribe(o -> {
                mBinding.swipeLayout.quickClose();
                RxDialogSureCancel editSureCancel = new RxDialogSureCancel(MineCollectActivity.this);
                editSureCancel.setContent("是否确定取消收藏？");
                editSureCancel.setCancel("确定");
                editSureCancel.setSure("取消");
                editSureCancel.getCancelView().setOnClickListener(dialog -> {
                    mViewModel.updateSmoke(item.getMuid());
                    editSureCancel.dismiss();
                });
                editSureCancel.getSureView().setOnClickListener(dialog -> {
                    editSureCancel.dismiss();
                });
                editSureCancel.show();
            });

            /**
             *  切换
             */
            RxView.clicks(mBinding.tvRechristen).subscribe(o -> {
                mBinding.swipeLayout.quickClose();
                if (FacilityClient2.mConnectState == BluetoothGatt.STATE_CONNECTED) {
                    RxDialogSureCancel editSureCancel = new RxDialogSureCancel(MineCollectActivity.this);
                    editSureCancel.setContent("是否确定切换为当前品牌香烟？");
                    editSureCancel.setCancel("确定");
                    editSureCancel.setSure("取消");
                    editSureCancel.getCancelView().setOnClickListener(dialog -> {
                        dealData(item);
                        editSureCancel.dismiss();
                    });
                    editSureCancel.getSureView().setOnClickListener(dialog -> {
                        editSureCancel.dismiss();
                    });
                    editSureCancel.show();
                } else {
                    ToastUtils.error("蓝牙未连接，暂不能切换品牌香烟");
                }
            });
        }
    }

    private void dealData(Collect item) {
        if (MyApp.getInstance().getDatabase().collectDao() != null && MyApp.getInstance().getDatabase().collectDao().getCollectInfoList() != null) {
            List<Collect> collects = MyApp.getInstance().getDatabase().collectDao().getCollectInfoList();
            for (int i = 0; i < collects.size(); i++) {
                if (item.getCode().equals(collects.get(i).getCode())) {
                    collects.get(i).setSelectCurrent(1);
                } else {
                    collects.get(i).setSelectCurrent(2);
                }
            }
            if (collects.size() > 0) {
                MyApp.getInstance().getDatabase().collectDao().deleteAll();
            }
            for (Collect collect : collects) {
                MyApp.getInstance().getDatabase().collectDao().insertSingle(collect);
            }
            adapter.setNewData(collects);

            ToastUtils.success("已经切换为当前品牌香烟！");
            EventBus.getDefault().post(new EventMessage("cutCigarette", ""));
        }
    }
}
